<?php

namespace Index\Controller;

use Think\Controller;
use Index\ViewModel;
use Index\Service;

/**
 * 说明：首页管理控制器
 * 作者：王楠
 * 创建日期：2017-09-12
 */
class IndexController extends CommonController {

    /**
     * 前置方法
     */
    public function __construct() {
	parent::__construct();
	$action = trim(__ACTION__, '/');
	$actions = explode('/', $action);
	$action = strtolower($actions[2]);
	if (empty($action)) {
	    $action = strtolower($actions[1]);
	}
	if ($action == 'index' || $action == 'admindetail' || $action == 'adminmodify') {
	    $system_name_abbr = $this->app_name;
	    $system_name = $this->app_name . C('SYSTEM_NAME');
	    $this->system_name_abbr = $system_name_abbr;
	    $this->system_name = $system_name;
	    $warning_box_switch = C('NUMBER_WARNING_SWITCH');
	    $show_warning_box = '0';
	    $numberModel = M('chat_usermembernum');
	    $number_count = $numberModel->where(array('state' => '1'))->count();
	    if ($number_count <= 0) {
		$show_warning_box = '1';
	    } else {
		$number_warning_count = C('NUMBER_WARNING_COUNT');
		$number_warning_percent = C('NUMBER_WARNING_PERCENT');
		$sectionModel = M('chat_usernumsection');
		$section = $sectionModel->where(array('state' => '3'))->order('start_id desc')->find();
		if (!empty($section)) {
		    $number_warning_count = (($section['end_id'] + 1) - $section['start_id']) / $number_warning_percent;
		}
		if ($number_count < $number_warning_count) {
		    $show_warning_box = '2';
		}
		$this->number_warning_count = $number_warning_count;
	    }
	    $this->show_warning_box = empty($warning_box_switch) ? '0' : $show_warning_box;
	    $login_type = $this->login_type;
	    $admin_id = $this->admin_id;
	    $admin_uid = $this->admin_uid;
	    $admin_username = $this->admin_username;
	    if ($admin_id && $admin_username) {
		if ($login_type == '2') {
		    $state_enum = getenumbykey('userlogin_state');
		    $viewModel = new ViewModel\UserViewModel();
		    $admin = $viewModel->where(array('user_uid' => $admin_uid))->where(array('is_agent' => '2', 'is_lock' => '1'))->find();
		    if ($admin != null) {
			$this->admin_name = $admin['user_name'];
			$this->admin_phone = $admin['phone'];
			$this->admin_state = $admin['is_lock'];
			$this->admin_ctime = $admin['ctime'];
			$admin_name = $this->admin_name;
			$admin_phone = $this->admin_phone;
			$admin_state = $this->admin_state;
			$admin_ctime = $this->admin_ctime;
		    }
		} else {
		    $state_enum = getenumbykey('admin_state');
		    $adminModel = M('chat_admin'); //管理员表
		    $adminroleModel = M('chat_adminrole'); //管理员角色表
		    $viewModel = new ViewModel\AdminViewModel();
		    $admin = $viewModel->where(array('id' => $admin_id))->where(array('state' => '1'))->find();
		    if ($admin == null) {
			$admin = $adminModel->where(array('id' => $admin_id))->where(array('state' => '1'))->find();
		    }
		    if ($admin != null) {
			$this->admin_role_id = $admin['role_id'];
			$this->admin_name = $admin['name'];
			$this->admin_phone = $admin['phone'];
			$this->admin_state = $admin['state'];
			$this->admin_ctime = $admin['ctime'];
			//可在页面上显示的值
			$admin_role_id = $this->admin_role_id;
			$admin_state = $this->admin_state;
			$admin_ctime = $this->admin_ctime;
			$this->admin_role_value = '超级管理员';
			if ($admin_role_id) {
			    $admin_name = $this->admin_name;
			    $admin_phone = $this->admin_phone;
			    $this->admin_role_value = $admin['role_name'];
			    if ($action == 'index') {
				$this->level_first_id = $admin['level_first_id'];
				$this->level_second_id = $admin['level_second_id'];
				$this->level_third_id = $admin['level_third_id'];
			    }
			}
		    }
		}
		if ($admin != null) {
		    $this->admin_name_value = empty($admin_name) ? $admin_username : $admin_name;
		    $this->admin_phone_value = $admin_phone;
		    $this->admin_state_value = empty($admin_state) ? '' : $state_enum[$admin_state];
		    $this->admin_ctime_value = date("Y年m月d日H时i分s秒", $admin_ctime);
		    $adminlogModel = M('chat_adminlog'); //管理员操作日志表
		    $adminlog = $adminlogModel->where(array('admin_id' => $admin_id, 'type' => '1'))->order('ctime desc')->find();
		    $this->admin_login_time = date("Y年m月d日H时i分s秒", $adminlog['ctime']);
		}
	    }
	}
    }

    /**
     * 首页框架
     */
    public function index() {
	$app_code = $this->app_code;
	$login_type = $this->login_type;
	$admin_uid = $this->admin_uid;
	$admin_id = $this->admin_id;
	$admin_username = $this->admin_username;
	$admin_role_id = $this->admin_role_id;
	if ($login_type == '2') {
	    $this->display();
	    exit();
	}
	if ($admin_id && $admin_username) {
//	    $model = M('chat_adminpower'); //管理员权限表
//	    $admin_role_id = $this->admin_role_id;
//	    $map['state'] = '1';
//	    $map['pid'] = '0';
//	    if ($admin_role_id) {
//		$level_first_id = $this->level_first_id;
//		$level_second_id = $this->level_second_id;
//		$level_third_id = $this->level_third_id;
//		$data = $model->where($map)->where(array('id' => array('in', $level_first_id)))->order('sort')->select();
//	    } else {
//		$data = $model->where($map)->order('sort')->select();
//	    }
//	    foreach ($data as $key => $value) {
//		$map['pid'] = $value['id'];
//		if ($admin_role_id) {
//		    $data2 = $model->where($map)->where(array('id' => array('in', $level_second_id)))->order('sort')->select();
//		} else {
//		    $data2 = $model->where($map)->order('sort')->select();
//		}
//		$data[$key]['data'] = $data2;
//	    }

	    if (!empty($app_code)) {
		$map['app_flag'] = array(array('exp', 'is null'), array('eq', '1'), 'or');
	    } else {
		$map['app_flag'] = array(array('exp', 'is null'), array('eq', '2'), 'or');
	    }
	    $map['state'] = '1';
	    $map_level_first = array();
	    $map_level_second = array();
	    if ($admin_role_id) {
		$level_first_id = $this->level_first_id;
		$level_second_id = $this->level_second_id;
		$level_third_id = $this->level_third_id;
		$map_level_first = array('id' => array('in', $level_first_id));
		$map_level_second = array('id' => array('in', $level_second_id));
	    }
	    $model = M('chat_adminpower');
	    $data = $model->where($map)->where($map_level_first)->where(array('pid' => array('eq', '0')))->order('sort asc, ctime asc, id asc')->select();
	    $data2 = $model->where($map)->where($map_level_second)->where(array('pid' => array('gt', '0')))->order('sort asc, ctime asc, id asc')->select();
	    foreach ($data as $key => $value) {
		$data_son = array();
		foreach ($data2 as $key2 => $value2) {
		    if ($value2['pid'] == $value['id']) {
			array_push($data_son, $value2);
		    }
		}
		$data[$key]['data'] = $data_son;
	    }
	}
	$this->assign('data', $data);
	$this->assign('app_code', $app_code);
	$this->display();
    }

    /**
     * 首页内容
     */
    public function home() {
	$today = strtotime(date('Y-m-d'));
	$userinfoModel = M('chat_userinfo'); //用户邀请表
	$usercalllogModel = M('chat_usercalllog'); //用户通话日志表
	$balancelogModel = M('chat_balancelog'); //账户余额日志表
	$app_code = $this->app_code;
	if (empty($app_code)) {
	    $app_code = I('app_code');
	}
	$login_type = $this->login_type;
	$admin_uid = $this->admin_uid;
	$map = array('_complex' => '1=1');
	$map['app_flag'] = $app_code;
	$map['ctime'] = array('egt', $today);
	if ($login_type == '2') {
	    $map['agent_uid'] = $admin_uid;
	}
	$data['user_sum'] = $userinfoModel->where($map)->count();   //今日用户增长量
	$data['user_sum'] = empty($data['user_sum']) ? '0' : (int) $data['user_sum'];
	$data['call_sum'] = $usercalllogModel->where($map)->where(array('state' => '1', 'type' => '1'))->count();  //今日通话增长量
	$data['call_sum'] = empty($data['call_sum']) ? '0' : (int) $data['call_sum'];
//	$data['money_out_sum'] = $balancelogModel->where($map)->where(array('state' => '1', 'type' => '1'))->sum('money');  //今日消费金额（金币）
//	$data['money_in_sum'] = $balancelogModel->where($map)->where(array('state' => '1', 'type' => '3'))->sum('money');  //今日收益金额（金币）
//	$data['money_recharge_sum'] = $balancelogModel->where($map)->where(array('state' => '1', 'type' => '2'))->sum('money');  //今日充值金额（金币）
//	$data['money_withdaw_sum'] = $balancelogModel->where($map)->where(array('state' => '1', 'type' => '4'))->sum('money');  //今日提现金额（金币）
//	$data['money_other_sum'] = $balancelogModel->where($map)->where(array('state' => '1', 'type' => '5'))->sum('money');  //今日其他金额（管理员更改等）（金币）
	$field = 'type, sum(money) as total';
	$group = 'type';
	$balancelog_sum = $balancelogModel->where($map)->where(array('state' => '1'))->field($field)->group($group)->select();
	foreach ($balancelog_sum as $key => $value) {
	    switch ($value['type']) {
		case '1':
		    $data['money_out_sum'] = $value['total'];
		    break;
		case '2':
		    $data['money_recharge_sum'] = $value['total'];
		    break;
		case '3':
		    $data['money_in_sum'] = $value['total'];
		    break;
		case '4':
		    $data['money_withdraw_sum'] = $value['total'];
		    break;
		case '5':
		    $data['money_other_sum'] = $value['total'];
		    break;
		default:
		    break;
	    }
	}
	$data['money_out_sum'] = empty($data['money_out_sum']) ? '0' : (int) $data['money_out_sum'];
	$data['money_in_sum'] = empty($data['money_in_sum']) ? '0' : (int) $data['money_in_sum'];
	$data['money_recharge_sum'] = empty($data['money_recharge_sum']) ? '0' : (int) $data['money_recharge_sum'];
	$data['money_withdraw_sum'] = empty($data['money_withdraw_sum']) ? '0' : (int) $data['money_withdraw_sum'];
	$data['money_other_sum'] = empty($data['money_other_sum']) ? '0' : (int) $data['money_other_sum'];
	$this->assign('data', $data);
	$this->assign('app_code', $app_code);
	$this->display();
    }

    public function hometotal() {
	$state_enum = getenumbykey('app_state');
	$state_arr = getarrbyenum($state_enum);
	$state = '1';
	$begintime = trim(I('txtbegintime'));
	$endtime = trim(I('txtendtime'));
	$keyword = trim(I('txtkeyword'));
	if (!empty($state)) {
	    $map['app_state'] = $state;
	}
	if (!empty($begintime) || !empty($endtime)) {
	    if (!empty($begintime) && !empty($endtime)) {
		$map['ctime'] = array('between', array(strtotime($begintime), strtotime($endtime) + 60));
	    } else if (!empty($begintime)) {
		$map['ctime'] = array('between', array(strtotime($begintime), time() + 60));
	    } else if (!empty($endtime)) {
		$map['ctime'] = array('between', array(0, strtotime($endtime) + 60));
	    }
	}
	if (!empty($keyword)) {
	    $where['id'] = array('eq', $keyword);
	    $where['app_flag'] = array('like', '%' . $keyword . '%');
	    $where['app_name'] = array('like', '%' . $keyword . '%');
	    $where['_logic'] = 'or';
	    $map['_complex'] = $where;
	}
	$model = M('chat_systemset');
	$total = $model->where($map)->count();
	$row = '10';
	$page = new Service\PageService($total, $row);
	$fpage = $page->fpage();
	$field = array(
	    'id', 'app_flag', 'app_logo', 'app_name', 'app_state', 'ctime'
	);
	$order = 'ctime desc, id desc';
	$data = $model->where($map)->limit($page->listfirst, $page->listRows)->field($field)->order($order)->select();
	foreach ($data as $key => $value) {
	    $data[$key]['ctime'] = date('Y-m-d H:i', $data[$key]['ctime']);
	}
	$search = array('statesel' => $state, 'keyword' => $keyword, 'begintime' => $begintime, 'endtime' => $endtime);
	$this->assign(array(
	    'data' => $data,
	    'fpage' => $fpage,
	    'total' => $total,
	    'search' => $search,
	    'statearr' => $state_arr,
	    'localhost_sub_url' => C('LOCALHOST_SUB_URL'),
	));
	$this->display();
    }

    public function appenter() {
	$app_code = I('app_code');
	if (empty($app_code)) {
	    $res = array('ret' => '1002', 'code' => '参数错误！');
	    return $this->ajaxReturn($res, 'json');
	}
	$model = M('chat_admin');
	$admin = $model->where(array('app_flag' => $app_code, 'admin_id' => array(array('exp', 'is null'), array('eq', ''), 'or')))->order('id desc')->find();
	if (empty($admin)) {
	    $res = array('ret' => '1002', 'code' => '未创建该项目超管账号！');
	    return $this->ajaxReturn($res, 'json');
	}
	$res = array('ret' => '1001', 'code' => '加载中…');
	return $this->ajaxReturn($res, 'json');
//	$username = $admin['username'];
//	$password = $admin['password'];
//	$data = array('username' => $username, 'password' => $password, 'app_code' => $app_code);
//	$url = "http://modemadm.86tudi.com/Login/loginsubmit";
//	$res = getcurl($url, $data);  //调用接口
//	$res = json_decode($res, true);
//	return $this->ajaxReturn($res, 'json');
    }

    /**
     * 今日收支明细记录
     */
    public function getmessagedata() {
	if (!IS_POST) {
	    $this->error('非法访问！');
	}
	$type_enum = getenumbykey('recharge_type');
	$today = strtotime(date('Y-m-d'));
	$app_code = $this->app_code;
	if (empty($app_code)) {
	    $app_code = I('app_code');
	}
	$login_type = $this->login_type;
	$admin_uid = $this->admin_uid;
	$page_size = I('pagesize', '5');
	$page = I('page', '0');
	$page_index = ($page - 1) * $page_size;
	$type = I('type');

	$map = array('_complex' => '1=1');
	$map['app_flag'] = $app_code;
	$map['state'] = '1';
	$map['ctime'] = array('egt', $today);
	if ($login_type == '2') {
	    $map['agent_uid'] = $admin_uid;
	}
	if (!empty($type)) {
	    $map['type'] = $type;
	}
	$field = array(
	    'user_id', 'user_uid', 'order_no', 'money', 'balance', 'ratio', 'state', 'type', 'toggle', 'content', 'ctime', 'user_id', 'user_logo', 'user_name', 'user_sex'
	);
	$viewModel = new ViewModel\BalancelogViewModel();
	$total = $viewModel->where($map)->count();
	$data = $viewModel->where($map)->limit($page_index, $page_size)->field($field)->order('ctime desc')->select();
	foreach ($data as $key => $value) {
//	    $user_name = $data[$key]['user_name'];
//	    $user_name_len = mb_strlen($user_name, 'utf8');
//	    if (!empty($user_name) && $user_name_len > 6) {
//		$data[$key]['user_name'] = mb_substr($user_name, 0, 2, 'utf8') . '…' . mb_substr($user_name, $user_name_len - 3, $user_name_len, 'utf8');
//	    }
//	    $content = $data[$key]['content'];
//	    $content_len = mb_strlen($content, 'utf8');
//	    if (!empty($content) && $content_len > 12) {
//		$data[$key]['content'] = mb_substr($content, 0, 5, 'utf8') . '…' . mb_substr($content, $content_len - 6, $content_len, 'utf8');
//	    }
	    $user_name = $data[$key]['user_name'];
	    $user_name_len = mb_strlen($user_name, 'utf8');
	    $user_name_text = $user_name;
	    if (!empty($user_name) && $user_name_len > 6) {
		$user_name_text = mb_substr($user_name, 0, 2, 'utf8') . '…' . mb_substr($user_name, $user_name_len - 3, $user_name_len, 'utf8');
	    }
//		$data[$key]['user_name_text'] = '<a href="javascript:void(0);" title="' . $user_name . '">' . $user_name_text . '</a>';
	    $data[$key]['user_name_text'] = $user_name_text;
	    $content = $data[$key]['content'];
	    $content_len = mb_strlen($content, 'utf8');
	    $content_text = $content;
	    if (!empty($content) && $content_len > 12) {
		$content_text = mb_substr($content, 0, 5, 'utf8') . '…' . mb_substr($content, $content_len - 6, $content_len, 'utf8');
	    }
//		$data[$key]['content_text'] = '<a href="javascript:void(0);" title="' . $content . '">' . $content_text . '</a>';
	    $data[$key]['content_text'] = $content_text;
	    $data[$key]['money'] = (int) $data[$key]['money'];
//	    $data[$key]['money'] = ($data[$key]['toggle'] == '1' ? '-' : '+') . (int) $data[$key]['money'];
	    $data[$key]['money_in'] = $data[$key]['toggle'] == '1' ? '' : (int) $data[$key]['money'];
	    $data[$key]['money_out'] = $data[$key]['toggle'] == '1' ? (int) $data[$key]['money'] : '';
	    $data[$key]['balance'] = (int) $data[$key]['balance'];
	    $data[$key]['type'] = $type_enum[$data[$key]['type']];
	    $data[$key]['ctime'] = date('Y-m-d H:i', $data[$key]['ctime']);
	}
//	$response = $data;
	$response = array('ret' => '1001', 'total' => $total, 'data' => $data);
	return $this->ajaxReturn($response, 'json');
    }

    public function admindetail() {

	$this->display();
    }

    public function adminmodify() {

	$this->display();
    }

    public function adminmodifysubmit() {
	if (!IS_POST) {
	    $this->error('非法访问！');
	}
	$admin_id = $this->admin_id;
	$name = trim(I('name'));
	$phone = trim(I('phone'));
	if (!empty($phone) && !preg_match("/^1[34578]{1}\d{9}$/", $phone)) {
	    $response = array('ret' => '1002', 'code' => '手机号码格式不正确！');
	    return $this->ajaxReturn($response, 'json');
	}
	$map['state'] = '1';
	$map['id'] = $admin_id;
	$model = M('chat_admin');
	if (!$model->where($map)->count()) {
	    $response = array('ret' => '1002', 'code' => '对不起，该账号可能已被删除！');
	    return $this->ajaxReturn($response, 'json');
	}
	$data['name'] = $name;
	$data['phone'] = $phone;
	if ($model->where(array('id' => $admin_id))->save($data)) {
	    $response = array('ret' => '1001', 'code' => '修改成功！');
	} else {
	    $response = array('ret' => '1001', 'code' => '修改成功！');
	}
	return $this->ajaxReturn($response, 'json');
    }

}

?>